package com.example.demo.service.imp;


import com.example.demo.dao.DeviceDao;
import com.example.demo.entity.Device;
import com.example.demo.service.DeviceService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

/**
 * @Date:2021/7/1 22:32
 * @Author:郑伟
 * @Version:1.1.0
 */
@Service
public class DeviceServiceImp implements DeviceService {
    @Autowired
    DeviceDao deviceDao;
    @Override
    public Device saveDevice(Device device) {
        return deviceDao.save(device);
    }
    public Optional<Device> findById(Integer id){

        Optional<Device> student=deviceDao.findById(id);
        return student;
    }


    public List<Device> findAll(){

        List<Device> myList=deviceDao.findAll();
        return myList;
    }

    public Page<Device> findByPage(int pageIndex, int pageSize){

        Sort sort =  Sort.by(Sort.Direction.DESC, "id");
        Pageable pageable = PageRequest.of(pageIndex, pageSize, sort);
        Page<Device> myList=deviceDao.findAll(pageable);

        return myList;

    }




    public Device add(Device student){
        deviceDao.save(student);
        return student;
    }

    public Device update(Device student){
        Device studentOld=deviceDao.getOne(student.getId());
        //todo sth....
        deviceDao.save(student);
        return student;
    }


    public int delete(Device student){

        try{

            deviceDao.delete(student);
        }catch (Exception e){

            //throw  e;
            return -1;
        }
        return 1;
    }

    public  int delete(Integer id){
        Device student=deviceDao.getOne(id);

        return delete(student);

    }
}
